package org.morning.open.connectionPool;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 工具类
 * 
 * @author SUN
 */
public class MyJDBCPoolUtil {

	private static Properties properties = new Properties();
	static ConnectionPool<Connection> pool = null;
	// 加载DBCP配置文件

	static {
		try {
			InputStream inStream = MyJDBCPoolUtil.class.getClassLoader()
					.getResourceAsStream("jdbc.properties");
			properties.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("dbUrl", properties.getProperty("url", ""));
			args.put("username", properties.getProperty("username", ""));
			args.put("password", properties.getProperty("password", ""));
			args.put("driverClassName",
					properties.getProperty("driverClassName", ""));
			ConnectionBuilder<Connection> connectionBuilder = new JdbcConnectionBuilder(
					args);
			pool = new ConnectionPool<Connection>("", 0, connectionBuilder, 3,
					100, 5);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从连接池中获取一个连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection connection = null;
		connection = pool.getConnection();
		try {
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * 释放连接
	 * 
	 * @param connection
	 */
	public static void releaseConnection(Connection connection) {
		pool.releaseConnection(connection);
	}

	/**
	 * 释放损坏了的连接
	 * 
	 * @param connection
	 */
	public static void releaseBrokenConnection(Connection connection) {
		pool.releaseBrokenConnection(connection);
	}

	public static void main(String[] args) {
		getConnection();
	}
}